<template>
  <view class="customer-service-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="客服人员信息" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 查询方式选择 -->
          <up-tabs :list="queryTypeList" :scrollable="false" @change="handleQueryTypeChange"></up-tabs>
          
          <!-- 搜索条件 -->
          <view class="search-section">
            <!-- 全部客服查询 -->
            <view v-if="currentQueryType === 0" class="search-item">
              <up-search v-model="searchForm.keyword" :clearabled="true" :showAction="true" 
                placeholder="请输入客服姓名" @search="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                </template>
              </up-search>
            </view>
            
            <!-- 按停车场查询 -->
            <view v-if="currentQueryType === 1" class="search-item">
              <up-search v-model="searchForm.parkingLot" :clearabled="true" :showAction="true" 
                placeholder="请输入停车场名称" @search="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                </template>
              </up-search>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 汇总数据 -->
      <view v-if="summaryData" class="summary-section">
        <view class="summary-item">
          <text class="summary-label">在线客服</text>
          <text class="summary-value count">{{ summaryData.onlineCount }}人</text>
        </view>
        <view v-if="currentQueryType === 1" class="summary-item">
          <text class="summary-label">当前停车场</text>
          <text class="summary-value parking">{{ summaryData.currentParkingLot || '全部' }}</text>
        </view>
        <view class="summary-item">
          <text class="summary-label">总客服数</text>
          <text class="summary-value total">{{ summaryData.totalCount }}人</text>
        </view>
      </view>

      <!-- 列表内容 -->
      <view class="customer-service-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              <text class="name">{{ item.name }}</text>
              <view class="status-badge" :class="{ 'online': item.isOnline, 'offline': !item.isOnline }">
                {{ item.isOnline ? '在线' : '离线' }}
              </view>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">手机号：</text>
                <text class="value phone">{{ item.phone }}</text>
              </view>
              <view class="item">
                <text class="label">管理停车场：</text>
                <text class="value">{{ item.parkingLots.join('、') }}</text>
              </view>
              <view class="item">
                <text class="label">工作时间：</text>
                <text class="value">{{ item.workTime }}</text>
              </view>
              <view class="item">
                <text class="label">今日处理工单：</text>
                <text class="value count">{{ item.todayTickets }}件</text>
              </view>
            </view>
            <view class="card-footer">
              <view class="operate">
                <up-button type="primary" text="联系客服" class="custom-style" 
                  @click="handleContact(item)"></up-button>
                <up-button type="default" text="查看详情" class="custom-style" 
                  @click="handleViewDetail(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 客服详情弹出层 -->
    <CustomerServiceDetailModal v-model:show="showDetailModal" :customer-service-info="selectedCustomerService" />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import CustomerServiceDetailModal from './components/CustomerServiceDetailModal.vue'

const { bool: showDetailModal, setTrue: openDetailModal, setFalse: closeDetailModal } = useBoolean();

// 查询方式选项卡数据
const queryTypeList = [
  { name: '全部客服' },
  { name: '按停车场查看' },
];
const currentQueryType = ref(0);

// 搜索表单数据
const searchForm = reactive({
  keyword: '',
  parkingLot: '',
});

// 汇总数据
const summaryData = ref(null);

// 选中的客服信息
const selectedCustomerService = ref(null);

// z-paging 组件引用
const paging = ref(null)

// 当前显示的列表数据
const currentList = ref([])

// 查询方式切换事件
const handleQueryTypeChange = (e) => {
  const newIndex = e.index;
  if (currentQueryType.value === newIndex) {
    return;
  }

  currentQueryType.value = newIndex;
  
  // 清空搜索表单
  searchForm.keyword = '';
  searchForm.parkingLot = '';
  
  // 清空列表和汇总数据
  currentList.value = [];
  summaryData.value = null;
  
  // 重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 搜索按钮点击事件
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 清空搜索
const handleClear = () => {
  if (currentQueryType.value === 0) {
    searchForm.keyword = '';
  } else {
    searchForm.parkingLot = '';
  }
  
  if (paging.value) {
    paging.value.reload();
  }
};

// 联系客服
const handleContact = (item) => {
  uni.makePhoneCall({
    phoneNumber: item.phone,
    success: () => {
      console.log('拨打电话成功');
    },
    fail: (err) => {
      console.error('拨打电话失败:', err);
      uni.showToast({
        title: '拨打电话失败',
        icon: 'none'
      });
    }
  });
};

// 查看详情
const handleViewDetail = (item) => {
  selectedCustomerService.value = item;
  openDetailModal();
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}

// 获取客服列表数据
const queryList = async (pageNo, pageSize) => {
  console.log(pageNo, pageSize, currentQueryType.value)

  const params = {
    pageNum: pageNo,
    pageSize,
    queryType: currentQueryType.value
  }

  // 添加搜索条件
  if (currentQueryType.value === 0 && searchForm.keyword) {
    params.keyword = searchForm.keyword;
  } else if (currentQueryType.value === 1 && searchForm.parkingLot) {
    params.parkingLot = searchForm.parkingLot;
  }

  await fetchList(params)
};

const fetchList = async (params) => {
  try {
    // 模拟API调用，实际项目中应该调用真实的API
    const mockData = generateMockData(params);
    
    paging.value.complete(mockData.records || [])
    
    // 设置汇总数据
    summaryData.value = mockData.summary;
  } catch (error) {
    paging.value.complete(false)
  }
}

// 生成模拟数据
const generateMockData = (params) => {
  const allCustomerServices = [
    {
      id: 1,
      name: '张小美',
      phone: '13800138001',
      parkingLots: ['万达广场停车场', '银泰中心停车场'],
      isOnline: true,
      workTime: '09:00-18:00',
      todayTickets: 15
    },
    {
      id: 2,
      name: '李小雅',
      phone: '13800138002',
      parkingLots: ['世贸天阶停车场'],
      isOnline: true,
      workTime: '09:00-18:00',
      todayTickets: 12
    },
    {
      id: 3,
      name: '王小慧',
      phone: '13800138003',
      parkingLots: ['朝阳大悦城停车场', '三里屯太古里停车场'],
      isOnline: false,
      workTime: '14:00-22:00',
      todayTickets: 8
    },
    {
      id: 4,
      name: '赵小敏',
      phone: '13800138004',
      parkingLots: ['国贸中心停车场'],
      isOnline: true,
      workTime: '09:00-18:00',
      todayTickets: 20
    },
    {
      id: 5,
      name: '钱小丽',
      phone: '13800138005',
      parkingLots: ['望京SOHO停车场', '中关村广场停车场'],
      isOnline: true,
      workTime: '10:00-19:00',
      todayTickets: 18
    }
  ];

  let filteredData = allCustomerServices;

  // 根据查询类型过滤
  if (params.queryType === 0) {
    // 全部客服 - 根据姓名过滤
    if (params.keyword) {
      filteredData = allCustomerServices.filter(item => 
        item.name.includes(params.keyword)
      );
    }
  } else if (params.queryType === 1) {
    // 按停车场查看 - 根据停车场过滤
    if (params.parkingLot) {
      filteredData = allCustomerServices.filter(item => 
        item.parkingLots.some(lot => lot.includes(params.parkingLot))
      );
    }
  }

  // 计算汇总数据
  const onlineCount = filteredData.filter(item => item.isOnline).length;
  const totalCount = filteredData.length;
  const currentParkingLot = params.parkingLot || null;

  return {
    records: filteredData,
    summary: {
      onlineCount,
      totalCount,
      currentParkingLot
    }
  };
};

// 页面挂载时获取数据
onMounted(() => {
  fetchList({
    pageNum: 1,
    pageSize: 10,
    queryType: 0
  })
});
</script>

<style scoped lang="scss">
.customer-service-list {
  padding: 20px;
}

.search-section {
  margin-top: 20rpx;
  
  .search-item {
    margin-bottom: 20rpx;
  }
}

.summary-section {
  display: flex;
  justify-content: space-around;
  padding: 30rpx 40rpx;
  margin: 20rpx;
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
  border-radius: 16rpx;
  box-shadow: 0 8rpx 32rpx rgba(82, 196, 26, 0.3);
  
  .summary-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .summary-label {
      font-size: 24rpx;
      color: rgba(255, 255, 255, 0.8);
      margin-bottom: 8rpx;
    }
    
    .summary-value {
      font-size: 32rpx;
      font-weight: bold;
      color: #fff;
      
      &.count {
        color: #fff;
      }
      
      &.parking {
        color: #ffd700;
        font-size: 24rpx;
        text-align: center;
      }
      
      &.total {
        color: #87ceeb;
      }
    }
  }
}

// 列表卡片样式
.list-item-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
  
  .card-header {
    padding: 24rpx 30rpx 16rpx;
    border-bottom: 1px solid #f5f5f5;
    
    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .name {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
      }
      
      .status-badge {
        padding: 4rpx 12rpx;
        border-radius: 12rpx;
        font-size: 22rpx;
        color: #fff;
        
        &.online {
          background: #52c41a;
        }
        
        &.offline {
          background: #d9d9d9;
          color: #666;
        }
      }
    }
  }
  
  .card-content-box {
    padding: 20rpx 30rpx;
    
    .content {
      .item {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          font-size: 26rpx;
          color: #666;
          flex-shrink: 0;
        }
        
        .value {
          font-size: 26rpx;
          color: #333;
          text-align: right;
          flex: 1;
          
          &.phone {
            color: #1890ff;
            font-weight: 500;
          }
          
          &.count {
            color: #52c41a;
            font-weight: bold;
          }
        }
      }
    }
    
    .card-footer {
      margin-top: 24rpx;
      padding-top: 20rpx;
      border-top: 1px solid #f5f5f5;
      
      .operate {
        display: flex;
        justify-content: flex-end;
        gap: 20rpx;
        
        .custom-style {
          border-radius: 8rpx;
          font-size: 24rpx;
          flex: 1;
        }
      }
    }
  }
}
</style>